package com.kamloo.stg.data.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PeriodDAO {
	
	private SQLiteDatabase m_database;
	private MySQLiteHelper m_dbHelper;
	public static final String TABLE_NAME  = "period";
	public static final String COLUMN_ID 	 = "_id";
	public static final String COLUMN_NAME	 = "name";		
	private String[] m_allColumns = { COLUMN_ID, COLUMN_NAME };
	
	public static final String TABLE_CREATE = 
			"CREATE TABLE " + 
		    TABLE_NAME + "(" + 
		    COLUMN_ID + " INTEGER PRIMARY KEY, " + 
		    COLUMN_NAME + " TEXT NOT NULL);";
	
	public PeriodDAO(Context context) {
		m_dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		m_database = m_dbHelper.getWritableDatabase();
	}

	public void close() {
		m_dbHelper.close();
	}
	
	
	public void add(Period period) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_ID, period.getId());
		values.put(COLUMN_NAME, period.getName());
		m_database.insert(TABLE_NAME, null, values);
	}
	
	public void delete(int id) {
		System.out.println("Period deleted with id: " + id);
		m_database.delete(TABLE_NAME, COLUMN_ID + " = " + id, null);
	}
	
	public Period select(int id) {
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, COLUMN_ID + " = " + id, 
									  null, null, null, null);
		
		if (cur != null)
			cur.moveToFirst();
		
		Period newPeriod = cursorToPeriod(cur);
		cur.close();
		return newPeriod;
	}
	
	public ArrayList<Period> selectAll(){
		ArrayList<Period> periods = new ArrayList<Period>();
		
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, 
				  					  null, null, null, null, null);

		if (cur != null) {
			cur.moveToFirst();
			while (!cur.isAfterLast()) {
				periods.add(cursorToPeriod(cur));
				cur.moveToNext();
			}
		}

		cur.close();
		return periods;
	}
	
	public void update(Period period) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_NAME, period.getName());
		m_database.update(TABLE_NAME, values, COLUMN_ID + " = " + period.getId(), null);
	}	
	
	private Period cursorToPeriod(Cursor cursor) {
		return new Period(cursor.getInt(0),
						  cursor.getString(1));
	}
}
